<?php
/**
 * 提现相关
 * User: wuhao
 * Date: 2017/5/8
 * Time: 17:12
 */
namespace app\backend\controller;

use app\backend\model\Bank;
use app\backend\model\Member;
use app\backend\model\Withdraw;
use Cache\Redis;
use think\Controller;

class WithdrawController extends Controller
{
    private $_memberId = null;
    private $_dtype    = null;

    public function __construct()
    {
        parent::__construct();
        $memberInfo = $this->getLoginInfo();
        $this->_memberId = $memberInfo['mid'];
        $this->_dtype    = $memberInfo['dtype'];
    }

    /**
     * 提现申请操作
     * @date   2017-05-10
     * @author wuhao
     *
     * @return json
     */
    public function withdrawApply()
    {
        $money        = I('post.money', 0, 'floatval');         //提现金额
        $accountType  = I('post.account_type', 0, 'intval');    //账户类型 0=银行卡 1=支付宝
        $account      = I('post.account', '', 'strval');        //账号
        $withdrawPwd  = I('post.withdraw_pwd', '', 'strval');   //提现密码
        //$money=123;$accountType=0;$account='1234567890123456';$withdrawPwd='14e1b600b1fd579f47433b88e8d85291';
        if (!is_numeric($money) || $money<=1) {
            $this->apiReturn(400, [], '提现金额有误');
        }
        if (!in_array($accountType, [0,1])) {
            $this->apiReturn(400, [], '账户类型有误');
        }
        if (!$account) {
            $this->apiReturn(400, [], '提现账号有误');
        }
        if (!$withdrawPwd) {
            $this->apiReturn(400, [], '请输入提现密码');
        }
        //金额*100，用分保存
        $moneyFen = fen($money);

        $bankModel = new Bank();
        $memberModel = new Member();

        $redis = new Redis();
        $key = "withdraw_apply:$this->_memberId";

        if ($redis->get($key)) {
            $this->apiReturn(409, [], '系统正在处理中...');
        }

        $redis->set($key, 1, 120);//加锁

        //获取用户的基本信息
        $memberInfo = $memberModel->getMemberInfoById($this->_memberId);
        //判断银行卡或支付宝是不是自己绑定的

        if ($accountType == 1) {//支付宝
            if ($memberInfo['alipay'] != $account) {
                $redis->rm($key);
                $this->apiReturn(401, [], '支付宝账号非自己绑定的');
            }
            $bankName = '支付宝';
            $bankCode = '';
        } else {//银行卡
            $bank = $bankModel->getBankCard($account);
            if (!$bank) {
                $redis->rm($key);
                $this->apiReturn(402, [], '该银行卡未绑定');
            }
            if ($bank['mid'] != $this->_memberId) {
                $redis->rm($key);
                $this->apiReturn(402, [], '非银行卡绑定人');
            }
            $bankCode = $bank['bank_code'];
            $bankInfo = $bankModel->getBankCodeInfoByCode($bank['bank_code']);
            $bankName = $bankInfo['bank'];
        }

        //获取用户余额
        $memberMoney = $memberModel->getMemberMoney($this->_memberId);
        //获取冻结金额
        $freezeMoney = $memberModel->getFreezeMoney($this->_memberId);
        //可提现余额
        $wdMoney = ($memberMoney > $freezeMoney) ? ($memberMoney - $freezeMoney) : 0;
        if ($wdMoney < $moneyFen) {
            $redis->rm($key);
            $this->apiReturn(403, [], '提现金额不能大于账户可提现余额');
        }

        //获取提现手续费率
        $feeBank = $memberInfo['bank_fee'];
        if (!$feeBank || $feeBank<0) {
            $redis->rm($key);
            $this->apiReturn(404, [], '提现手续费率有误');
        }


        $MAX_ERROR_TIME = 5;
        //验证提现密码
        if (!$memberInfo['withdraw_pwd']) {
            $redis->rm($key);
            $this->apiReturn(405, [], '请先设置提现密码');
        } else {//有设置提现密码先判断错误次数
            //判断是否超过最大限制
            if ($memberInfo['wd_err_no']>=$MAX_ERROR_TIME && (time()-strtotime($memberInfo['wd_err_time']))<300) {
                $redis->rm($key);
                $this->apiReturn(405, [], "提现密码错误次数超过$MAX_ERROR_TIME"."次，半小时内不可申请");
            }

            //判断提现密码是否正确
            if ($withdrawPwd != $memberInfo['withdraw_pwd']) {//密码错误
                $redis->rm($key);
                //更新错误次数及时间
                $memberModel->updateUser($memberInfo['id'], ['wd_err_no' => $memberInfo['wd_err_no']+1, 'wd_err_time' => date('Y-m-d H:i:s')]);
                $this->apiReturn(405, [], '提现密码有误，请重新输入');
            } else {//密码正确
                $memberModel->updateUser($memberInfo['id'], ['wd_err_no' => 0, 'wd_err_time' => '0000-00-00 00:00:00']);
            }
        }
        //新增log
        //将提现动作写入日志
        $logData = json_encode([
            'ip'                       => get_client_ip(),
            'memberId'                 => $this->_memberId,
            'withdraw_deposit_in_yuan' => $money,
            'bank_fee'                 => $feeBank,
            'microtime'                => microtime(true)
        ]);
        zft_log('withdraw/apply', $logData);

        //新增记录
        $withdrawModel = new Withdraw();
        $res = $withdrawModel->addRecord($this->_memberId, $moneyFen, $feeBank, $accountType, $bankName, $bankCode, $account);
        $redis->rm($key);
        if ($res['code'] == 200) {
            $this->apiReturn(200, [], '提现申请成功');
        } else {
            zft_log('withdraw/apply', 'code:'.$res['code'].', msg:'.$res['msg']);
            $this->apiReturn(201, [], '提现申请失败');
        }
    }


    /**
     * 获取提现申请列表
     * @date   2017-05-10
     * @author wuhao
     *
     * @return
     */
    public function getList()
    {
        $searchType = I('post.type', 0, 'intval');      //搜索类型  0=按用户名 1=按平台账号
        $content    = I('post.content', '', 'strval');  //搜索内容
        $status     = I('post.status', -1, 'intval');    //提现状态 -1全部 0=提现中（未处理） 1=提现成功  2=拒绝提现  3=提现失败(处理了，但出现了xx问题)
        $page       = I('post.page', 1, 'intval');      //页数
        $pageSize   = I('post.page_size', 10, 'intval'); //每页个数
        if (!in_array($status, [-1,0,1,2,3]) || !$page || !$pageSize) {
            $this->apiReturn(400, [], '参数错误');
        }
        $withdrawModel = new Withdraw();
        $res = $withdrawModel->getWithdrawList($this->_memberId, $this->_dtype, $status, $searchType, $content, $page, $pageSize);
        if ($res) {
            $midArr = array_unique(array_column($res['list'], 'mid'));
            $memberModel = new Member();
            $mInfo = $memberModel->getMemberInfoById($midArr, 'id, username, nickname');
            foreach ($res['list'] as $k =>$v) {
                $res['list'][$k]['actual_money']  = yuan($v['actual_money']);
                $res['list'][$k]['service_money'] = yuan($v['service_money']);
                $res['list'][$k]['money']         = yuan($v['money']);
                foreach ($mInfo as $m) {
                    if ($v['mid'] == $m['id']) {//获取平台账号和用户名
                        $res['list'][$k]['nickname'] = $m['nickname'];
                        $res['list'][$k]['username'] = $m['username'];
                    }
                }
            }
            $this->apiReturn(200, $res, '');
        } else {
            $this->apiReturn(201, [], '没有数据');
        }
    }

    /**
     * 获取提现申请记录详情
     * @date   2017-05-12
     * @author wuhao
     *
     * @return
     */
    public function getDetail()
    {
        $id = I('post.id', '', 'intval');  //提现申请id
        if (!$id) {
            $this->apiReturn(400, [], '参数错误');
        }
        $withdrawModel = new Withdraw();
        $res = $withdrawModel->getWithdrawById($id, 'mid, money, actual_money, service_money, bank_name, account');
        if ($res) {
            if ($this->_dtype != 0 && $this->_memberId != $res['mid']) {
                $this->apiReturn(202, [], '无权查看');
            }
            $res['money']         = yuan($res['money']);
            $res['actual_money']  = yuan($res['actual_money']);
            $res['service_money'] = yuan($res['service_money']);
            $this->apiReturn(200, $res, '');
        } else {
            $this->apiReturn(201, [], '没有数据');
        }
    }
}